package com.whisper.application.app.web.controller.front;

import com.whisper.application.app.web.service.TokenService;
import com.whisper.application.service.domain.VrUser;
import com.whisper.application.service.service.IVrUserService;
import com.whisper.common.config.WhisperConfig;
import com.whisper.common.core.controller.BaseController;
import com.whisper.common.core.domain.AjaxResult;
import com.whisper.common.core.domain.entity.SysUser;
import com.whisper.common.exception.operate.OperateException;
import com.whisper.common.security.model.LoginUser;
import com.whisper.common.security.util.SecurityUtils;
import com.whisper.common.utils.StreamUtil;
import com.whisper.common.utils.StringUtils;
import com.whisper.common.utils.file.FileUploadUtils;
import com.whisper.common.utils.file.MimeTypeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

import static com.whisper.common.security.util.SecurityUtils.*;

/**
 * 前台用户信息Controller
 * 
 * @author whisper
 * @date 2024-01-07
 */
@RestController
@RequestMapping("/front/user")
public class FrontUserController extends BaseController
{
    @Autowired
    private IVrUserService vrUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public void avatar(@RequestParam("avatarfile") MultipartFile file, HttpServletResponse response) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(WhisperConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (vrUserService.updateUserAvatar(loginUser.getUsername(), WhisperConfig.getFrontPrefix() + avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                StreamUtil.response(response, ajax);
            }
        }
        throw new OperateException("上传图片异常，请联系管理员");
    }

    @PutMapping("/info")
    public void updateInfo(@RequestBody VrUser user) throws Exception
    {
        if (Objects.isNull(user)) {
            throw new IllegalArgumentException("参数异常！");
        }
        vrUserService.updateVrUser(user);
        LoginUser loginUser = getLoginUser();
        loginUser.setUser(createLoginUser(user));
        tokenService.setLoginUser(loginUser);
    }

    @PostMapping("/resetPwd")
    public int resetPwd(@RequestBody VrUser user, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        if (!StringUtils.isEmpty(user.getPhonenumber())) {
            user.setPhonenumber(user.getPhonenumber());
        }
        if (!StringUtils.isEmpty(user.getEmail())) {
            user.setEmail(user.getEmail());
        }
        user.setUpdateBy(getUsername());
        vrUserService.resetPwd(user);
        VrUser vrUser = vrUserService.selectVrUserById(user.getId());
        LoginUser loginUser = getLoginUser();
        loginUser.setUser(createLoginUser(vrUser));
        if (!StringUtils.isEmpty(user.getPassword())) {
            logoutSuccessHandler.onLogoutSuccess(request, response, SecurityUtils.getAuthentication());
        }
        return 0;

    }

    public SysUser createLoginUser(VrUser user)
    {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user, sysUser);
        sysUser.setUserId(user.getId());
        sysUser.setUserName(user.getUsername());
        sysUser.setDeptId(null);
        sysUser.setNickName(user.getNickname());
        sysUser.setPhonenumber(user.getPhonenumber());
        sysUser.setEmail(user.getEmail());
        return sysUser;
    }

}
